#!/usr/bin/python

# Rotate.py by Bandoine 10/10/2008

# need hdaps kernel module loaded
# need nvidia drivers
# need in Xorg.conf device section :
#	Option  "RandRRotation" "True"

import os,time,re,sys;

#file containing the computer position
POS_FILE = '/sys/devices/platform/hdaps/position'
#regex for parsing position
POS_RX = re.compile('^\((-?\d+),(-?\d+)\)$')

#command used for rotate display
normal='xrandr -o normal'
left='xrandr -o left'
right='xrandr -o right'

#global vars
current_display_pos = 0
		 
def get_current_pos():
	"""return a 2-tuple with the X and the Y position"""
	pos = open(POS_FILE).read()
	match = POS_RX.match(pos)
	return (int(match.groups()[0]), int(match.groups()[1]))

def switch_screen_pos(xpos):
	"""switch the display orientation according to the computer position"""
	global current_display_pos
	if (xpos > 430 and xpos < 600):	
		if current_display_pos != 0:
			print "switching display to normal"
			os.system(normal)
			time.sleep(1)
			current_display_pos = 0
	elif xpos < 430:
		if current_display_pos != 1:
			print "switching display to left"
			os.system(left)
			time.sleep(1)
			current_display_pos = 1
	elif xpos > 600:
		if current_display_pos != 2:
			print "switching display to right"
			os.system(right)
			time.sleep(1)
			current_display_pos = 2
				
def main():
	while True:
		time.sleep(1)
		xpos=(get_current_pos()[0] * -1)
		print "X : " + str(xpos)
		switch_screen_pos(xpos)

main()
